package com.pengxh.cmake.uart

import android.os.ParcelFileDescriptor
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.InputStream
import java.io.OutputStream

class SerialPort(device: File, baudRate: Int, flags: Int) {

    private var mFd: ParcelFileDescriptor
    var inputStream: InputStream
    var outputStream: OutputStream

    init {
        System.loadLibrary("serial_port")

        if (!device.canRead() || !device.canWrite()) {
            try {
                val su = Runtime.getRuntime().exec("/system/bin/su")
                val cmd = "chmod 666 ${device.absolutePath} \n exit \n"
                su.outputStream.write(cmd.toByteArray())
                if (su.waitFor() != 0 || !device.canRead() || !device.canWrite()) {
                    throw SecurityException()
                }
            } catch (e: Exception) {
                e.printStackTrace()
                throw SecurityException()
            }
        }
        mFd = open(device.absolutePath, baudRate, flags)
        inputStream = FileInputStream(mFd.fileDescriptor)
        outputStream = FileOutputStream(mFd.fileDescriptor)
    }

    fun closeSerialPort() {
        close()
    }

    private external fun open(path: String, baudRate: Int, flags: Int): ParcelFileDescriptor

    private external fun close()
}